import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Query,
} from '@nestjs/common';
import { FeaturesService } from './features.service';
import { CreateFeatureDto } from './dto/create-feature.dto';
import { UpdateFeatureDto } from './dto/update-feature.dto';
import { SwaggerErr, SwaggerOk } from 'src/decorators/swagger.decorator';
import { API_CODES, API_MSGS } from 'src/const/api.const';
import { Api } from 'src/utils/api';
import { CasesService } from 'src/cases/cases.service';
import {   ApiOperation,  ApiQuery, ApiTags } from '@nestjs/swagger';
 
import * as _ from 'lodash';
import { FeatureScenarioService } from 'src/feature-scenario/feature-scenario.service';

@ApiTags('Features接口')
@Controller('features')
export class FeaturesController {
  constructor(
    private readonly featuresService: FeaturesService,
    private fsService:FeatureScenarioService

  ) {}

  @Post('/')
  @SwaggerOk()
  async create(@Body() featureData: CreateFeatureDto) {
    const isExist = await this.featuresService.featureIsExists(
      featureData.feature,
    );
    if (isExist) {
      return Api.err(
        API_CODES['FEATURE_EXIST'],
        API_MSGS[API_CODES['FEATURE_EXIST']],
      );
    } else {
      //创建features
      await this.featuresService.create(featureData);
      return Api.ok();
    }
  }

  // 更新所有数据
  @Post('/updateBatch')
  async updateBatch(@Body() featureDatas: CreateFeatureDto[]) {
    featureDatas.map(async (item) => {
      if(item.id>0){
        const feature = await this.featuresService.findOne(item.id);
        let isUpdate = false;
        if (item.feature != feature.feature) {
          feature.feature = item.feature;
          isUpdate = true;
        }
        if (item.sort != feature.sort) {
          feature.sort = item.sort;
          isUpdate = true;
        }
        if (isUpdate) {
          this.featuresService.update(item.id, feature);
        }
      }
    });

    return Api.ok();
  }

  @Get()
  @SwaggerOk(Array<CreateFeatureDto>)
  @ApiQuery({
    name: 'searchKey',
    required: false,
    type: String,
  })
  async findAll(@Query() query) {
    const { searchKey } = query;
    // 查询所有的features
    const data = await this.featuresService.findAll(searchKey);
    return Api.ok(data);
  }

  //查询单个feature数据
  @Get(':id')
  @SwaggerOk(CreateFeatureDto)
  @SwaggerErr(API_CODES.FEATURE_NO_EXIST)
  async findOne(@Param('id') id: string) {
    const testFeature = await this.featuresService.findOne(+id);
    if (testFeature) {
      return Api.ok(testFeature);
    } else {
      return Api.err(API_CODES.FEATURE_NO_EXIST);
    }
  }

  @Patch(':id')
  @SwaggerOk()
  async update(
    @Param('id') id: number,
    @Body() updateFeatureDto: UpdateFeatureDto,
  ) {
    // console.log("id---", id, typeof id);
    await this.featuresService.update(+id, updateFeatureDto);
    return Api.ok();
  }

  @Delete(':id')
  @SwaggerOk()
  async remove(@Param('id') id: string) {
    const data =await this.fsService.findManyByFid(+id);
    if(  data.length > 0 ){
      return Api.err(API_CODES.FEATURE_RELATED_SCENARIO,  
         API_MSGS[API_CODES.FEATURE_RELATED_SCENARIO]
       )
    }else{
      // 执行删除逻辑
      const res1 = await this.featuresService.remove(+id);
      return Api.ok();
    }
  }

  @ApiOperation({
    summary: '根据feature名称查询下属的scenario的步骤,供cypress用',
  })
  @Get('/subscenario/:feature')
  // @ApiParam({ name: 'feature', required: false })
  async getScenario(@Param('feature') feature: string) {
    const data = await this.featuresService.queryScenarioByFeature(
      _.trim(feature),
    );
    // 返回结果
    // [{scenario:'', cases:'' }]
    const res = [];
    data.map((d) => {
      res.push(d.scenario);
    });
    return Api.ok(res);
  }


  @ApiOperation({
    summary: '根据feature名称查询下属的scenario的步骤,供cypress用',
  })
  @Get('/subscenario2/:feature')
  // @ApiParam({ name: 'feature', required: false })
  async getScenario2(@Param('feature') feature: string) {
    const data = await this.featuresService.queryScenarioByFeature(
      _.trim(feature),
    );
    // 返回结果 testCase组成的数组
    // [{ }]
    let res = [];
    // console.log("data---", data);
    data.map((d) => {
      // console.log("d--",d)
      res = res.concat( d.scenario.cases);
    });
    return Api.ok(res);
  }


  @ApiOperation({ summary: '根据FeatureId查询所拥有的scenarios' })
  @Post('/scenario/:featureId')
  async getScenariosByFeatureId(@Param('featureId') featureId: string) {
    const data = await this.featuresService.queryScenariosByFeatureId(
      +featureId,
    );
    return Api.ok(data);
  }

  @Get('/scenarios/All')
  @SwaggerOk(Object)
  async findAllScenario() {
    // 查询所有的features
    const data = await this.featuresService.findAllScenario();
    // console.log("data-71--", data);
    return Api.ok(data);
  }

  @ApiOperation({ summary: '查询feature为key他们对应的scenarios数组' })
  @Get('/scenarios/Map')
  async findFeatureScenariosMap() {
    //
    const data = await this.featuresService.findFeatureScenariosMap();
    const res = [];
    data.map( item=>{
      // console.log("item--",item);
      const {feature, hasPreAction} = item;
      const _scenario = [];
      item.scenarios.map( s=>{
        _scenario.push(s.scenario.scenario);
      });
      // console.log("_scenario---", _scenario);
      res.push({
        feature,
        hasPreAction,
        scenarios: _scenario
      })
    });

    return Api.ok(res);
  }


}
